<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\Db;
use cmf\controller\AdminBaseController;
use app\admin\model\AdminMenuModel;
use Hooklife\ThinkphpWechat\Wechat;
use EasyWeChat\Foundation\Application;
class WuyeController extends AdminBaseController
{

    public function _initialize(){
        $this->user_id = cmf_get_current_admin_id();
//        $this->query = Db::name('wx_info')->where('user_id', $this->user_id)->count();
        $this->query ='1';
        $this->info = Db::name('wx_info')->where('user_id', $this->user_id)->find();
        if (!empty($this->info)) {
            $options = [
                'app_id' => $this->info['app_id'],         // AppID
                'secret' => $this->info['app_secret'],     // AppSecret
                'token' => $this->info['token'],          // Token
                'aes_key' => $this->info['aes_key'],                 // EncodingAESKey，安全模式下请一定要填写！！！
            ];
            $this->app = new Application($options);
            $this->app_id = $this->info['app_id'];
            $this->secret = $this->info['app_secret'];
            $this->temp_id = $this->info['temp_id'];
        } else {
            if($this->user_id != '1'){
                echo "<div id='notice'><h1>还没有添加公众号，请先添加公众号</h1><br><a href='http://".$_SERVER['HTTP_HOST']."/Admin/wechat/editPublic.html'>点击跳转配置公众号</a></div>";
            }

        }
    }
    public function _empty($name){
        return $this->fetch($name);
    }

//    物业公告
    public function noticeList(){
        if($this->query){
            $keyword = $this->request->param('keyword');
            $cate_id = $this->request->param('cate_id');
            $where['user_id'] = $this->user_id;
            if(!empty($keyword)){
                $where['title|desc'] = ['like',"%".$keyword."%"];
            }
            if (!empty($cate_id)){
                $where['cate_id'] = $cate_id;
            }
            $list = Db::name('wy_notice')->where($where)->order('id desc')->paginate(20);
            $cate = Db::name('wy_notice_cate')->select();
            $this->assign('cate',$cate);
            $this->assign('list', $list);
            $this->assign('page', $list->render());
            return $this->fetch();
        }
    }
    public function noticeAdd(){
        $id = input('id');
        if(!empty($id)){
            $list = Db::name('wy_notice')->where('id',$id)->find();
        }else{
            $list = '';
        }
        $cate = Db::name('wy_notice_cate')->select();
        $this->assign('cate',$cate);
        $this->assign('cates',$cate);
        $this->assign('list',$list);
        return $this->fetch();
    }
    public function noticeSvae(){
        $id = input('id');
        $content = input('content');
        $data['content'] = $content;
        $data = input();
        $is_show = input('is_show');
        $data['time'] = time();
        $data['user_id'] = $this->user_id;
        $data['app_id'] = $this->info['app_id'];

        if(isset($is_show)){
            $data['is_show'] = 1;
        }else{
            $data['is_show'] = 0;
        }
        if(!empty($id)){
            $res = Db::name('wy_notice')->where('id',$id)->update($data);
            if($res){
                $this->success('更新成功','noticeList');
            }
        }else{
            $res = Db::name('wy_notice')->insert($data);
            if($res){
                $this->success('添加成功','noticeList');
            }
        }

    }
    public function noticeDel(){
        $id = input('id');
        $res = Db::name('wy_notice')->delete($id);
        if($res){
            $this->success('删除成功','noticeList');
        }
    }

//    曝光台
    public function exposureList(){
        if($this->query){
            $keyword = $this->request->param('keyword');
            $where['user_id'] = $this->user_id;
            if($keyword){
                $where['title|desc'] = ['like',"%".$keyword."%"];
                $list = Db::name('wy_exposure')->where($where)->order('id desc')->paginate(20);
            }else{
                $list = Db::name('wy_exposure')->where($where)->order('id desc')->paginate(20);
            }
            $this->assign('list', $list);
            $this->assign('page', $list->render());
            return $this->fetch();
        }
    }
    public function exposureSvae(){
        $data = input();
        $data['time'] = time();
        $data['user_id'] = $this->user_id;
        $data['app_id'] = $this->info['app_id'];
        $res = Db::name('wy_exposure')->insert($data);
        if($res){
            $this->success('添加成功','exposureList');
        }
    }
    public function exposureDel(){
        $id = input('id');
        $res = Db::name('wy_exposure')->delete($id);
        if($res){
            $this->success('删除成功','noticeList');
        }
    }

    public function baoxiu(){
        if ($this->query){
            $where['wy_wy_baoxiu.user_id'] = $this->user_id;
            $keyword = $this->request->param('keyword');
            $question_id = $this->request->param('question_id');
            if(!empty($keyword)){
                $where['wy_wy_baoxiu.desc'] = ['like',"%".$keyword."%"];
            }
            if(!empty($cate_id)){
                $where['wy_wy_baoxiu.question_id'] = $question_id;
            }
//            $list = Db::name('wy_baoxiu')->where($where)->order('id desc')->paginate(20);
            $cate = Db::name('wy_baoxiu_question')->select();
            $this->assign('cate',$cate);

            $list = Db::table('wy_wy_baoxiu')
                ->alias('a')
                ->join('wy_wx_fans w','a.openid = w.openid')
                ->join('wy_wy_baoxiu_question q','a.question_id = q.id')
                ->where($where)
                ->order('time desc')
                ->field('a.*,w.nickname,w.phone,q.name')
                ->paginate(20);
            $this->assign('list1',$list);
            return $this->fetch();
        }
    }
    public function del(){
        $id = input('id');

        $table = input('table');
        $res = Db::name($table)->delete([$id]);
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    public function saveBaoxiuQuestion(){
        $data = input();
        $data['user_id'] = $this->user_id;
        if(!empty($this->user_id)){
            $res = Db::name('wy_baoxiu_question')->insert($data);
            if($res){
                $this->success('添加报修问题成功','baoxiu');
            }
        }
    }
//    快递
    public function express(){
        $keyword = $this->request->param('keyword');
        $where['user_id'] = $this->user_id;
        if($keyword){
            $where['title|desc'] = ['like',"%".$keyword."%"];
            $list = Db::name('wy_express')->where($where)->order('id desc')->select();
        }else{
            $list = Db::name('wy_express')->where($where)->order('id desc')->select();
        }
        $this->assign('express', $list);
        return $this->fetch();
    }

    public function expressAdd(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('imgsrc');

        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
            if($info){
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                $data['imgsrc'] = $info->getSaveName();
                $data['name'] = $this->request->param('name');
                $data['url'] = $this->request->param('url');
                $data['user_id'] = $this->user_id;
                $res = Db::name('wy_express')->insert($data);
                if($res){
                    $this->success('添加快递信息成功','express','',1);
                }
            }else{
                // 上传失败获取错误信息
                $this->error('没有上传快递图片');
            }
        }
        return $this->fetch();
    }

//    业务预约
    public function reservation(){
        if($this->query){
            $keyword = $this->request->param('keyword');
            $where['user_id'] = $this->user_id;
            if($keyword){
                $where['title|desc'] = ['like',"%".$keyword."%"];
                $list = Db::name('wy_reservation')->where($where)->order('id desc')->select();
            }else{
                $list = Db::name('wy_reservation')->where($where)->order('id desc')->select();
            }
            $this->assign('express', $list);
            return $this->fetch();
        }
    }
    public function reservationSave(){
        if($this->query){
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('imgsrc');
            // 移动到框架应用根目录/public/uploads/ 目录下
            if($file){
                $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
                if($info){
                    // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                    $data['imgsrc'] = $info->getSaveName();
                }else{
                    // 上传失败获取错误信息
                    echo $file->getError();
                }
            }
            $data['desc'] = $this->request->param('desc');
            $data['phone'] = $this->request->param('phone');
            $data['user_id'] = $this->user_id;
            $data['time'] = time();
            $res = Db::name('wy_reservation')->insert($data);
            if($res){
                $this->success('添加预约业务信息成功','reservation','',1);
            }
        }
    }

    public function carousel(){
        echo "<style type='text/css'>#notice{display: none;}</style>";
        $keyword = $this->request->param('keyword');

        if($keyword){
            $where['title|desc'] = ['like',"%".$keyword."%"];
            $list = Db::name('wy_carousel')->where($where)->order('id desc')->select();
        }else{
            $list = Db::name('wy_carousel')->order('id desc')->select();
        }
        $this->assign('express', $list);
        return $this->fetch();
    }
    public function carouselAdd(){
        echo "<style type='text/css'>#notice{display: none;}</style>";
        $id = input('id');
        if(!empty($id)){
            $res = Db::name('wy_carousel')->where('id',$id)->find();
            return view('',[
                'res'=>$res,
            ]);
        }
        return view();
    }
    public function carouselSave(){
        echo "<style type='text/css'>#notice{display: none;}</style>";
        $id = input('id');
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('imgsrc');
        $data['desc'] = $this->request->param('desc');
        $data['id'] = $this->request->param('id');
        $data['url'] = $this->request->param('url');
        $data['user_id'] = $this->user_id;
        $data['time'] = time();
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
            if($info){
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                $data['imgsrc'] = $info->getSaveName();
            }else{
                // 上传失败获取错误信息
                $this->error($file->getError(),'carousel');
            }
        }
        if(empty($id)){
            $res = Db::name('wy_carousel')->insert($data);
        }else{
            $res = Db::name('wy_carousel')->where('id',$id)->update($data);
        }

        if($res){
            $this->success('添加轮播图成功','carousel','',1);
        }
    }

//    缴费
    public function paylist(){
        $where = '';
        if($this->user_id != 1){
            $where['a.user_id'] = $this->user_id;
        }
        $keyword = $this->request->param('keyword');
        if(!empty($keyword)){
            $where['c.nickname|c.remark'] = ['like',"%".$keyword."%"];
        }
        $cate_id = $this->request->param('cate_id');
        if (!empty($cate_id)){
            $where['a.cate_id'] = $cate_id;
        }
        $is_pay = $this->request->param('is_pay');
        if (!empty($is_pay)){
            $where['a.is_pay'] = $is_pay;
        }
        $start_time = $this->request->param('start_time');
        $end_time = $this->request->param('end_time');
        
        if(!empty($start_time) && !empty($end_time)){
            $where['a.time'] = ['between time',$start_time.','.$end_time];
        }elseif(!empty($start_time)){
            $where['a.time'] = ['EGT',strtotime($start_time.'0:0:0')];
        }elseif (!empty($end_time)){
            $where['a.time'] = ['ELT',strtotime($end_time.'23:59:59')];
        }


        $list = Db::table('wy_pay')
            ->alias('a')
            ->join('wy_pay_cate b','a.cate_id = b.id')
            ->join('wy_wx_fans c','a.openid = c.openid')
            ->where($where)
            ->field('a.*,b.name as cate_name,c.openid,c.nickname,c.remark')
            ->order('is_pay asc,id desc')
            ->select();
        foreach ($list as $k=>$v){
            foreach ($list as $k1=>$v1) {
                if(($v['total']==$v1['total'])&&($v['time']==$v1['time'])&&($k!=$k1)){
                    unset($list[$k]);
                }
            }
        }
        $data = Db::table('wy_pay')
            ->alias('a')
            ->join('wy_pay_cate b','a.cate_id = b.id')
            ->join('wy_wx_fans c','a.openid = c.openid')
            ->where($where)
            ->field('a.*,b.name as cate_name,c.openid,c.nickname,c.remark')
            ->order('is_pay asc,id desc')
            ->select();
        $cate = Db::name('pay_cate')->where('user_id',$this->user_id)->select();
        return view('',[
            'list'=>$list,
            'data'=>$data,
            'cate'=>$cate,
            'keyword'=>$keyword,
            'start_time'=>$start_time,
            'end_time'=>$end_time,
        ]);
    }
    public function payAdd(){
        $id = input('id');
        $list = '';
        $resList = '';
        $fans = '';
        $cate = '';
        if(!empty($id)){
            $list = Db::name('pay')->where('id',$id)->find();
            $resList = Db::name('pay')->where(['time'=>$list['time'],'total'=>$list['total']])->select();
//            halt($resList);
//            $this->assign('list',$resList);
        }
        $where['user_id'] = $this->user_id;
        $cate = Db::name('pay_cate')->where($where)->select();
        $fans = Db::name('wx_fans')->where($where)->select();
        return view('',[
            'cate'=>$cate,
            'fans'=>$fans,
            'list'=>$list,
            'resList'=>$resList,
        ]);
    }
    public function payDetail(){
        $id = input('id');
        $list = '';
        $resList = '';
        $fans = '';
        $cate = '';
        if(!empty($id)){
            $list = Db::name('pay')->where('id',$id)->find();
            $resList = Db::name('pay')->where(['time'=>$list['time'],'total'=>$list['total']])->select();
//            halt($resList);
//            $this->assign('list',$resList);
        }
        $where['user_id'] = $this->user_id;
        $cate = Db::name('pay_cate')->where($where)->select();
        $fans = Db::name('wx_fans')->where($where)->select();
        return view('',[
            'cate'=>$cate,
            'fans'=>$fans,
            'list'=>$list,
            'resList'=>$resList,
        ]);
    }
    public function paySvae(){
        $id = input('id/a');

        if(!empty($id)){
            $resData = '';
            $data['id'] = $id;
            $data['total'] = input('total/a');
            $data['cate_id'] = input('cate_id/a');
            $data['num'] = input('num/a');
            $data['start_time'] = input('start_time/a');
            $data['end_time'] = input('end_time/a');
            for ($i=0;$i<count($data['id']);$i++){
                foreach ($data as $k=>$v){
                    $resData[$i][$k] = $v[$i];
                }
            }
            foreach ($resData as $k1=>$v1){
                $res = Db::name('pay')->update($v1);
            }

        }else{
            $data = input();
            $data['total'] = input('total');
            $data['cate_id'] = input('cate_id/a');
            $data['num'] = input('num/a');
            $data['start_time'] = input('start_time/a');
            $data['end_time'] = input('end_time/a');
            $save ='';
                foreach ($data['cate_id'] as $k=>$cate_id){
                        foreach ($data['num'] as $k1=>$num){
                            $save[$k]['num'] = $data['num'][$k];
                            $save[$k]['openid'] = $data['openid'];
                            $save[$k]['cate_id'] = $cate_id;
                            $save[$k]['openid'] = $data['openid'];
                            $save[$k]['total'] = $data['total'];
                            $save[$k]['start_time'] = $data['start_time'][$k];
                            $save[$k]['end_time'] = $data['end_time'][$k];
                            $save[$k]['user_id'] = $this->user_id;
                            $save[$k]['time'] = time();
                        }
                }
//                dump($data);
//                halt($save);
            $res = Db::name('pay')->insertAll($save);
        }

        $this->success('更改成功','paylist');
    }
    public function payCateSvae(){
        $data = input();
        $data['user_id'] = $this->user_id;
        $res = Db::name('pay_cate')->insert($data);
        if($res){
            $this->success('添加成功','payCateAdd');
        }else{
            $this->error('添加失败');
        }
    }
    public function paydel(){
        $id = input('id');
        $id = rtrim($id, ',');
        $res = Db::name('pay')->delete($id);
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    public function payChange(){
        $id = input('id');
        $res = Db::name('pay')->where(['id'=>['in',$id]])->update(['is_pay'=>'1']);
        if($res){
            $this->success('添加成功','zuAdd');
        }else{
            $this->error('添加失败');
        }
    }
    public function paySend(){
        $openid = input('openid');
        $is_pay = input('is_pay');
        if($is_pay == 1){
            $this->success('该用户已经缴纳该项费用','paylist','','1');
        }else{
            $notice = $this->app->notice;
            $userId = $openid;
            $templateId = $this->temp_id;
            $url = "http://".$_SERVER['HTTP_HOST']."/portal/wuye/code?app_id=".$this->app_id."&url=pay";
            $payInfo = Db::name('pay')->where(['openid'=>$openid,'is_pay'=>0])->select();
            $keyword2 = '';
            if(!empty($payInfo)){
                foreach ($payInfo as $k => $v){
                    $keyword2 += $payInfo[$k]['num'];
                }
            }
            $time = Db::name('pay')->where(['openid'=>$openid,'is_pay'=>0])->order('time desc')->field('time')->limit(1)->select();

            $keyword1 = date('Y-m-d',$time[0]['time']);
            $data = array(
                "first"  => "你好，您的最新缴费账单已经生成！",
                "keyword1"   => $keyword2 . "元",
                "keyword2"  =>$keyword1,
                "remark" => "请您及时缴费！",
            );
            $res = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();
            if($res){
                $this->success('发送成功','paylist','','1');
            }
        }
    }

    public function Dels(){
        $ids = input('ids/a');
        $table = input('table');
        if(!empty($ids)){
            end($ids);
            $key_last = key($ids);
            $res='';
            foreach ($ids as $k => $v){
                Db::name($table)->where('id',$v)->delete();
                if ( $k = $key_last ) {
                    $res = 1;
                }
            }
            if($res == 1){
                $this->success('删除成功！','');
            }
        }
    }

    //二维数组去掉重复值,并保留键值
    function array_unique_fb($array2D){
        foreach ($array2D as $k=>$v){
            $v=join(',',$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
            $temp[$k]=$v;
        }
        $temp=array_unique($temp); //去掉重复的字符串,也就是重复的一维数组
        foreach ($temp as $k => $v){
            $array=explode(',',$v); //再将拆开的数组重新组装
            //下面的索引根据自己的情况进行修改即可
            $temp2[$k]['id'] =$array[0];
            $temp2[$k]['openid'] =$array[1];
            $temp2[$k]['cate_id'] =$array[2];
            $temp2[$k]['desc'] =$array[3];
            $temp2[$k]['num'] =$array[4];
            $temp2[$k]['is_pay'] =$array[5];
            $temp2[$k]['time'] =$array[6];
            $temp2[$k]['user_id'] =$array[7];
            $temp2[$k]['total'] =$array[8];
            $temp2[$k]['cate_name'] =$array[9];
            $temp2[$k]['nickname'] =$array[10];
            $temp2[$k]['remark'] =$array[11];
        }
        return $temp2;
    }

    public function wfcx(){
        $getData = input();
        if(!empty($getData)){
            Db::name('user')->where('id','1')->update($getData);
            $this->success('添加成功！','');
        }
        $data = Db::name('user')->where('id','1')->find();
        return view('',[
            'data'=>$data,
        ]);
    }

    public function four(){
        $getData = input();
        if(!empty($getData)){
            Db::name('four')->where('id','1')->update($getData);
            $this->success('添加成功！','');
        }
        $data = Db::name('four')->where('id','1')->find();
        return view('',[
            'data'=>$data,
        ]);
    }


    public function zu(){
        $where = '';
        $cate_id = input('cate_id');
        if(!empty($cate_id)){
            $where['a.cate_id'] = $cate_id;
        }
        $cate = Db::name('rental_can_cate')->select();
        $res = Db::table('wy_rental_can')
            ->alias('a')
            ->join('wy_rental_can_cate b','a.cate_id=b.id','left')
            ->where($where)
            ->field('a.*,b.name as cateName')
            ->paginate(20);
        $page = $res->render();
        return view('',[
            'res'=>$res,
            'cate'=>$cate,
            'page'=>$page,
        ]);
    }
    public function zuAdd(){
        $id = input('id');
        $res = '';
        if(!empty($id)){
            $res = Db::name('rental_can')->where('id',$id)->find();
        }
        $cate = Db::name('rental_can_cate')->select();
        return view('',[
            'res'=>$res,
            'cate'=>$cate,
            'id'=>$id,
        ]);
    }

    public function zuSave(){
        $data = input();
        $res = Db::name('rental_can')->insert($data);
        if($res){
            $this->success('添加成功','zuAdd');
        }else{
            $this->error('添加失败');
        }
    }

    public function zuge(){
        $type = input('type');
//        halt($type);
        $where = '';
        if(!empty($type)){
            $where['a.type'] = $type;
        }
        $res = Db::table('wy_rental')
            ->alias('a')
            ->join('wy_hat_province c','a.province=c.provinceID','left')
            ->join('wy_hat_city d','a.city=d.cityID','left')
            ->join('wy_hat_area e','a.area=e.areaID','left')
            ->join('wy_wx_info f','a.app_id=f.app_id','left')
            ->where($where)
            ->field('a.*,c.province as Pname,d.city as Cname,e.area as Aname,f.name as wxName')
            ->paginate(20);
        return view('',[
            'res'=>$res,
        ]);
    }

    public function zugeAdd(){
        $id = input('id');
        $res = Db::table('wy_rental')
            ->alias('a')
            ->join('wy_hat_province c','a.province=c.provinceID','left')
            ->join('wy_hat_city d','a.city=d.cityID','left')
            ->join('wy_hat_area e','a.area=e.areaID','left')
            ->where('a.id',$id)
            ->field('a.*,c.province as Pname,c.provinceID,d.city as Cname,d.cityID,e.area as Aname,e.areaID')
            ->find();
        $can = Db::name('rental_can')->select();
        return view('',[
            'res'=>$res,
            'can'=>$can,
            'id'=>$id,
        ]);
    }

    public function zugeSave(){
        $id = input('id');
        $data = input();
        $res = Db::name('rental')->where('id',$id)->update($data);
        if($res){
            $this->success('添加成功','zuge');
        }else{
            $this->error('添加失败');
        }
    }

    public function chexian(){
        $res = Db::table('wy_chexian')
            ->alias('a')
            ->join('wy_wx_fans b','a.openid=b.openid','left')
            ->field('a.*,b.phone,b.nickname')
            ->select();
        return view('',[
            'res'=>$res
        ]);
    }

    public function market(){
        $res = Db::table('wy_wy_market')
            ->alias('a')
            ->join('wy_wx_info b','a.user_id=b.user_id','left')
            ->join('wy_wx_fans c','a.openid=c.openid','left')
            ->field('a.*,b.name as wxName,c.nickname,c.remark')
            ->select();
        return view('',[
            'data'=>$res,
        ]);
    }

    public function yezhu(){
//        

        $userId = cmf_get_current_admin_id();
        if($userId!=1){
            $where['a.user_id'] = $userId;
        }else{
            $where = '';
        }
        $keyword = input('keyword');
        if(!empty($keyword)){
            $where['a.remark|a.nickname|a.address'] = ['like','%'.$keyword.'%'];
        }
        $res = Db::name('wx_fans')
            ->alias('a')
            ->join('wx_info b','a.user_id=b.user_id','left')
            ->where('louhao','neq','null')
            ->where('danyuanhao','neq','null')
            ->where('louceng','neq','null')
            ->where('fangjianhao','neq','null')
            ->where($where)
            ->field('a.*,b.name as Bname')
            ->select();
        return view('',[
            'res'=>$res,
            'keyword'=>$keyword,
        ]);
    }
    public function yezhuAdd(){
        $id = input('id');
        $data = Db::name('wx_fans')->where('id',$id)->find();
        return view('',[
            'data'=>$data,
            'id'=>$id,
        ]);
    }
    public function yezhuSave(){
        $id = input('id');
        $data = input();
        $res = Db::name('wx_fans')->where('id',$id)->update($data);
        if($res){
            $this->success('编辑成功','yezhu');
        }else{
            $this->error('编辑失败');
        }
    }
}
